package dao;

import bean.Student;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import java.util.List;

public class StudentDAOImpl implements StudentDAO {
    private Session session;
    private Transaction transaction;
    private boolean completed;

    public StudentDAOImpl(Session session) {
        this.session = session;
    }

    @Override
    public boolean add(Student student) {
        try {
            transaction = session.beginTransaction();
            session.save(student);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
            session.close();
        }
        return completed;
    }

    @Override
    public boolean modify(Student student) {
        try {
            transaction = session.beginTransaction();
            session.update(student);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
            session.close();
        }
        return completed;
    }

    @Override
    public boolean remove(int studentId) {
        try {
            transaction = session.beginTransaction();
            Student student = session.get(Student.class, studentId);
            session.delete(student);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
            session.close();
        }
        return completed;
    }

    @Override
    public List<Student> queryAll() {
        List<Student> students = null;
        try {
            @SuppressWarnings("unchecked")
            Query<Student> query = session.createQuery("FROM Student");
            students = query.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
        return students;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Student query(int studentId) {
        Student student;
        try {
            Query<Student> query = session.createQuery("FROM Student WHERE studentId=" + studentId);
            student = (Student) query.list().get(0);
        } catch (Exception e) {
            student = null;
            e.printStackTrace();
        } finally {
            session.close();
        }
        return student;
    }
}
